#!/usr/bin/env python3
"""
Self Validation Analyzer for Intelligent Rules V2.0
深度自我验证分析器，发现违背规则和不一致的地方

Usage: python tools/self_validation_analyzer.py
"""

import os
import sys
import yaml
from pathlib import Path
from typing import Dict, List, Any, Set

class SelfValidationAnalyzer:
    """自我验证分析器"""
    
    def __init__(self, project_root: Path = None):
        self.project_root = project_root or Path(__file__).parent.parent
        self.violations = []
        self.inconsistencies = []
        self.missing_components = []
        self.recommendations = []
        
    def run_comprehensive_analysis(self) -> Dict[str, Any]:
        """运行综合自我验证分析"""
        
        print("🔍 启动智能闭环自我验证分析")
        print("=" * 70)
        print("🎯 目标：发现违背规则和项目定位不一致的地方")
        print()
        
        # 1. 分析modules目录问题
        self._analyze_modules_violations()
        
        # 2. 检查项目定位一致性
        self._check_project_positioning_consistency()
        
        # 3. 验证工具和规则的对齐性
        self._validate_tools_rules_alignment()
        
        # 4. 检查目录结构合理性
        self._check_directory_structure_rationality()
        
        # 5. 分析文档和实现的一致性
        self._analyze_documentation_implementation_consistency()
        
        # 生成自我修复建议
        return self._generate_self_repair_recommendations()
    
    def _analyze_modules_violations(self):
        """分析modules目录违规问题"""
        print("📦 分析 modules/ 目录违规问题...")
        
        modules_dir = self.project_root / "modules"
        if not modules_dir.exists():
            self.violations.append("modules目录不存在")
            return
        
        expected_modules = ["ai_module", "web_module", "mobile_module", "enterprise_module"]
        
        for module_name in expected_modules:
            module_dir = modules_dir / module_name
            if not module_dir.exists():
                self.violations.append(f"缺少模块: {module_name}")
                continue
            
            # 检查模块内容
            self._check_module_content(module_name, module_dir)
    
    def _check_module_content(self, module_name: str, module_dir: Path):
        """检查单个模块内容"""
        
        print(f"  🔍 检查 {module_name}...")
        
        contents = list(module_dir.iterdir())
        
        # 检查是否只有README
        if len(contents) == 1 and contents[0].name == "README.md":
            self.violations.append(f"❌ {module_name}: 只有README.md，缺少实际规则和指导内容")
            self.missing_components.append({
                "module": module_name,
                "missing": ["rules/", "templates/", "configs/", "tools/"],
                "severity": "high"
            })
        elif len(contents) == 0:
            self.violations.append(f"❌ {module_name}: 完全空目录")
            self.missing_components.append({
                "module": module_name,
                "missing": ["README.md", "rules/", "templates/", "configs/", "tools/"],
                "severity": "critical"
            })
        else:
            # 检查模块结构完整性
            expected_structure = ["README.md", "rules", "templates", "configs"]
            missing = []
            
            for expected in expected_structure:
                if not (module_dir / expected).exists():
                    missing.append(expected)
            
            if missing:
                self.inconsistencies.append(f"🟡 {module_name}: 缺少 {', '.join(missing)}")
    
    def _check_project_positioning_consistency(self):
        """检查项目定位一致性"""
        print("\n🎯 检查项目定位一致性...")
        
        # 检查README中的定位描述
        readme_path = self.project_root / "README.md"
        if readme_path.exists():
            with open(readme_path, 'r', encoding='utf-8') as f:
                readme_content = f.read()
            
            # 检查是否突出"通用底座"定位
            if "通用底座" not in readme_content:
                self.inconsistencies.append("README.md未强调'通用底座'定位")
            
            # 检查是否避免"项目生成器"误解
            problematic_phrases = ["生成项目", "创建项目", "项目脚手架"]
            for phrase in problematic_phrases:
                if phrase in readme_content:
                    self.inconsistencies.append(f"README.md包含可能误导的表述: '{phrase}'")
    
    def _validate_tools_rules_alignment(self):
        """验证工具和规则的对齐性"""
        print("\n🔧 验证工具和规则对齐性...")
        
        tools_dir = self.project_root / "tools"
        
        # 检查是否存在违背"通用底座"定位的工具
        problematic_tools = [
            "web_project_setup.py",
            "ai_project_setup.py", 
            "enterprise_setup.py",
            "project_generator.py"
        ]
        
        for tool_name in problematic_tools:
            tool_path = tools_dir / tool_name
            if tool_path.exists():
                self.violations.append(f"❌ 存在违背定位的工具: {tool_name}")
        
        # 检查是否缺少符合定位的工具
        required_tools = [
            "integration_validator.py",
            "rules_guide_generator.py",
            "config_validator.py"
        ]
        
        for tool_name in required_tools:
            tool_path = tools_dir / tool_name
            if not tool_path.exists():
                self.missing_components.append({
                    "component": f"tools/{tool_name}",
                    "type": "essential_tool",
                    "severity": "high"
                })
    
    def _check_directory_structure_rationality(self):
        """检查目录结构合理性"""
        print("\n📁 检查目录结构合理性...")
        
        # 检查空目录或功能不明确的目录
        suspicious_dirs = []
        
        for item in self.project_root.iterdir():
            if item.is_dir():
                contents = list(item.rglob("*"))
                actual_files = [f for f in contents if f.is_file()]
                
                if len(actual_files) == 0:
                    suspicious_dirs.append(f"空目录: {item.name}")
                elif len(actual_files) < 3 and item.name not in ["docs", "templates"]:
                    suspicious_dirs.append(f"内容稀少: {item.name} ({len(actual_files)}个文件)")
        
        if suspicious_dirs:
            self.inconsistencies.extend(suspicious_dirs)
    
    def _analyze_documentation_implementation_consistency(self):
        """分析文档和实现的一致性"""
        print("\n📚 分析文档和实现一致性...")
        
        # 检查文档中提到的功能是否已实现
        docs_dir = self.project_root / "docs"
        
        if docs_dir.exists():
            for doc_file in docs_dir.glob("*.md"):
                try:
                    with open(doc_file, 'r', encoding='utf-8') as f:
                        content = f.read()
                    
                    # 检查文档中提到的工具是否存在
                    if "tools/" in content:
                        # 提取工具引用（简单的正则匹配）
                        import re
                        tool_references = re.findall(r'tools/(\w+\.py)', content)
                        
                        for tool_name in tool_references:
                            tool_path = self.project_root / "tools" / tool_name
                            if not tool_path.exists():
                                self.inconsistencies.append(f"文档引用不存在的工具: tools/{tool_name}")
                
                except Exception as e:
                    self.inconsistencies.append(f"无法分析文档: {doc_file.name}")
    
    def _generate_self_repair_recommendations(self) -> Dict[str, Any]:
        """生成自我修复建议"""
        
        print("\n" + "=" * 70)
        print("📊 自我验证分析报告")
        print("=" * 70)
        
        # 显示违规问题
        if self.violations:
            print(f"\n❌ 严重违规 ({len(self.violations)}个):")
            for violation in self.violations:
                print(f"  • {violation}")
        
        # 显示不一致问题
        if self.inconsistencies:
            print(f"\n⚠️ 不一致问题 ({len(self.inconsistencies)}个):")
            for inconsistency in self.inconsistencies:
                print(f"  • {inconsistency}")
        
        # 显示缺失组件
        if self.missing_components:
            print(f"\n🔧 缺失组件 ({len(self.missing_components)}个):")
            for missing in self.missing_components:
                if isinstance(missing, dict):
                    print(f"  • {missing.get('module', missing.get('component'))}: {missing.get('missing', missing.get('type'))}")
                else:
                    print(f"  • {missing}")
        
        # 生成修复建议
        self._generate_repair_recommendations()
        
        # 显示修复建议
        if self.recommendations:
            print(f"\n💡 自动修复建议 ({len(self.recommendations)}个):")
            for i, rec in enumerate(self.recommendations, 1):
                print(f"  {i}. {rec['title']}")
                print(f"     描述: {rec['description']}")
                print(f"     优先级: {rec['priority']}")
                print()
        
        # 总结
        total_issues = len(self.violations) + len(self.inconsistencies) + len(self.missing_components)
        print(f"📈 问题总结:")
        print(f"  总问题数: {total_issues}")
        print(f"  严重违规: {len(self.violations)}")
        print(f"  不一致: {len(self.inconsistencies)}")
        print(f"  缺失组件: {len(self.missing_components)}")
        
        health_score = max(0, 100 - total_issues * 5)
        print(f"  项目健康度: {health_score}/100")
        
        if total_issues == 0:
            print(f"  状态: ✅ 项目完全符合规则")
        elif total_issues < 5:
            print(f"  状态: 🟡 项目基本健康，有少量改进空间")
        else:
            print(f"  状态: 🔴 项目需要重要改进")
        
        return {
            "violations": self.violations,
            "inconsistencies": self.inconsistencies,
            "missing_components": self.missing_components,
            "recommendations": self.recommendations,
            "health_score": health_score,
            "total_issues": total_issues
        }
    
    def _generate_repair_recommendations(self):
        """生成具体修复建议"""
        
        # 基于发现的问题生成修复建议
        
        # 修复modules目录问题
        empty_modules = [mc for mc in self.missing_components if isinstance(mc, dict) and mc.get('module')]
        if empty_modules:
            self.recommendations.append({
                "title": "完善modules目录结构",
                "description": "为空的模块目录创建完整的规则、模板和配置文件",
                "priority": "high",
                "action": "create_module_structure"
            })
        
        # 修复工具违规问题
        tool_violations = [v for v in self.violations if "工具" in v]
        if tool_violations:
            self.recommendations.append({
                "title": "移除违背定位的工具",
                "description": "删除项目生成器类型的工具，保持通用底座定位",
                "priority": "critical",
                "action": "remove_inappropriate_tools"
            })
        
        # 修复文档不一致
        doc_issues = [i for i in self.inconsistencies if "文档" in i or "README" in i]
        if doc_issues:
            self.recommendations.append({
                "title": "统一文档和定位表述",
                "description": "确保所有文档都强调'通用底座'定位，避免误导性表述",
                "priority": "medium",
                "action": "align_documentation"
            })
        
        # 修复目录结构问题
        structure_issues = [i for i in self.inconsistencies if "目录" in i or "空" in i]
        if structure_issues:
            self.recommendations.append({
                "title": "优化目录结构",
                "description": "移除空目录，整合功能相似的目录",
                "priority": "low",
                "action": "optimize_structure"
            })

def main():
    """主程序"""
    print("🔧 Intelligent Rules V2.0 自我验证分析器")
    print("深度分析项目违规和不一致问题")
    print()
    
    analyzer = SelfValidationAnalyzer()
    result = analyzer.run_comprehensive_analysis()
    
    # 根据分析结果确定退出码
    if result["total_issues"] == 0:
        exit_code = 0
    elif result["total_issues"] < 5:
        exit_code = 1
    else:
        exit_code = 2
    
    print(f"\n🎯 自我验证完成，退出码: {exit_code}")
    sys.exit(exit_code)

if __name__ == "__main__":
    main() 